package com.businessportal.web.controllers.authenticate;

import com.businessportal.web.common.AuthHelper;
import com.businessportal.web.dataaccess.entities.Login;
import com.businessportal.web.dataaccess.services.UserService;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.*;
import java.io.IOException;

/**
 * Created by Vadim on 9/16/14.
 */

@WebServlet(urlPatterns = "/securepages/loginform.do")
public class AuthorizationController extends HttpServlet {

    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        try
        {
            String login = req.getParameter("login");//"admin";
            String passw = req.getParameter("password");//"bullst38";

            boolean isError = false;

            if (null == login || login.isEmpty())
            {
                req.setAttribute("ErrorLogin", "Field Login is empty!");
                isError = true;
            }
            if(null == passw || passw.isEmpty())
            {
                req.setAttribute("ErrorPassw", "Field Password is empty!");
                isError = true;
            }

            Login user = UserService.INSTANCE.CheckLoginPass(login, passw);

            if(!isError && null != user){
                HttpSession session = req.getSession();

                String cookieText = AuthHelper.generateCookieToken(login);

                session.setAttribute("user", user);

                session.setMaxInactiveInterval(30*60);
                Cookie userName = new Cookie("user", cookieText);
                userName.setMaxAge(30*60);
                resp.addCookie(userName);

            } else {
                req.setAttribute("Error", "You entered wrong password or login");
                isError = true;
            }

            if(isError)
            {
                req.getRequestDispatcher("/securepages/authorization.jsp").forward(req, resp);
            }
            else
            {
                req.removeAttribute("ErrorLogin");
                req.removeAttribute("ErrorPassw");
                resp.sendRedirect("/securepages/admin_portal.do");
            }

        }
        catch(Exception e)
        {
            System.out.println(e.getMessage());
        }
    }

    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        getServletContext().getRequestDispatcher("/securepages/authorization.jsp").forward(req, resp);
    }
}
